package com.zoweunion.mechanic.util;

import cn.jpush.api.push.PushResult;
import com.alibaba.fastjson.JSON;
import com.zoweunion.mechanic.dao.app.OrderDao;
import com.zoweunion.mechanic.plugins.jpush.JiguangPush;
import com.zoweunion.mechanic.service.app.PushMessageRecordService;
import com.zoweunion.mechanic.service.base.BaseService;
import com.zoweunion.mechanic.service.base.MessageRecordService;
import com.zoweunion.mechanic.util.constants.PushConstants;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class JiGuangPushUtil extends BaseService {

    @Autowired
    private MessageRecordService messageRecordService;
    @Autowired
    private JiguangPush jiguangPush;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private PushMessageRecordService pushMessageRecordService;

    public String creditLimitPush(Map<String, Object> reqmap) {
        Map<String, Object> othersMap = null;
        if (reqmap.get("credit_limit_consumption") != null) {
            othersMap = new HashMap<>();
            othersMap.put(PushConstants.KEY_CREDIT_LIMIT_CONSUMPTION, reqmap.get("credit_limit_consumption").toString());
        }
        return this.wrap(reqmap, PushConstants.KEY_CREDIT_LIMIT, reqmap.get("credit_limit").toString(), othersMap,1);
    }

    public String push(Map<String, Object> reqmap) {
        String orderId = reqmap.get("order_id").toString();

        String parentId = orderDao.getParentId(orderId);

        if (parentId != null) {

            orderId = parentId;
        }
        Map<String, Object> othersMap = null;
        if (reqmap.get("order_status") != null) {
            othersMap = new HashMap<>();
            othersMap.put(PushConstants.KEY_ORDER_STATUS, reqmap.get("order_status").toString());
        }
        return this.wrap(reqmap, PushConstants.KEY_ORDER_ID, orderId, othersMap,1);
    }

    public String pushJumpUrl(Map<String, Object> reqmap) {
        String jumpUrl = reqmap.get("jump_url").toString();
        Map<String, Object> othersMap = null;
        if (reqmap.get("order_status") != null) {
            othersMap = new HashMap<>();
            othersMap.put(PushConstants.KEY_ORDER_STATUS, reqmap.get("order_status").toString());
        }
        return this.wrap(reqmap, PushConstants.KEY_JUMP_URL, jumpUrl, othersMap, 2);
    }

    public String pushCurrency(Map<String, Object> reqmap) {
        return this.wrap(reqmap, null, null, null, null);
    }

    private String wrap(Map<String, Object> reqmap, String key, String value, Map<String, Object> otherParams, Integer type) {
        Map<String, Object> extraParamsMap = null;
        try {

            extraParamsMap = new HashMap<>();
            extraParamsMap.put(key, value);
            if (otherParams!= null) {
                extraParamsMap.putAll(otherParams);
            }
            String extraParams = JSON.toJSONString(extraParamsMap);

            Integer sendType = reqmap.containsKey("type") ? Integer.valueOf(reqmap.get("type").toString()) : 0;
            reqmap.putAll(this.generateMessageRecord(reqmap.get("current_user_id").toString(), reqmap.get("alias").toString(),
                    reqmap.get("msg").toString(), sendType, "YD", extraParams));
            messageRecordService.addMessageRecord(reqmap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String alias = reqmap.get("alias").toString();
        String msg = reqmap.get("msg").toString();
        String pushTime = DateUtil.formatTime(LocalDateTime.now());
        Map<String, Object> message;
        if (type == null) {
            message = this.pushMessageCurrencyParams(alias, pushTime, msg);
        } else if (type == 1) {
            message = this.pushMessageOrderIdParams(alias, pushTime, msg);
        } else if (type == 2) {
            message = this.pushMessageCarJumpUrlParams(alias, pushTime, msg);
        } else {
            return "failure";
        }
        Map<String, String> paramsMap = null;
        if (otherParams != null) {
            paramsMap = new HashMap<>();
            paramsMap.put(PushConstants.KEY_ORDER_STATUS, (String) otherParams.get(PushConstants.KEY_ORDER_STATUS));
        }
        PushResult pushResult = this.publishMessagePush(message, key, value, paramsMap, reqmap.get("id").toString());
        if (pushResult != null && pushResult.isResultOK()) {
            return "success";
        } else {
            return "failure";
        }
    }

    private Map<String, Object> generateMessageRecord(String userId, String alias, String msg, Integer sendType, String client, String extraParams) {
        Map<String, Object> params = new HashMap<>(16);
        params.put("user", userId);
        params.put("receive_user", alias);
        params.put("context", msg);
        params.put("send_type", sendType);
        params.put("client", client);
        params.put("extra_params", extraParams);
        return params;
    }


    /**
     * 发布审核消息批量推送
     *
     * @param messageList
     */
    public void buyinfoPublishCheckMessagePush(List<Map<String, Object>> messageList) {
        for (Map<String, Object> message : messageList) {
            this.buyinfoPublishCheckMessagePush(message);
        }
    }

    /**
     * 租售发布审核消息推送
     *
     * @param message
     */
    public PushResult buyinfoPublishCheckMessagePush(Map<String, Object> message) {
        String key = null, value = "";
        if (message.get("push_key") != null) {
            key = message.get("push_key").toString();
        }
        if (message.get("push_extra_value") != null) {
            value = message.get("push_extra_value").toString();
        }
        return this.publishMessagePush(message, key, value);
    }

    /**
     * 消息批量推送
     *
     * @param messageList
     * @param key
     */
    public void publishMessagePush(List<Map<String, Object>> messageList, String key, String value) {
        for (Map<String, Object> message : messageList) {
            this.publishMessagePush(message, key, value);
        }
    }

    /**
     * 消息批量推送
     *
     * @param messageList
     * @param key
     */
    public void publishMessagePush(List<Map<String, Object>> messageList, String key, String value, String messageId) {
        for (Map<String, Object> message : messageList) {
            this.publishMessagePush(message, key, value, messageId);
        }
    }

    /**
     * 消息推送 alias
     *
     * @param message
     * @param key
     */
    public PushResult publishMessagePush(Map<String, Object> message, String key, String value, String messageId) {
        return this.publishMessagePush(message, key, value, null, messageId);
    }

    /**
     * 消息推送 alias
     *
     * @param message
     * @param key
     */
    public PushResult publishMessagePush(Map<String, Object> message, String key, String value, Map<String, String> otherParams, String messageId) {
        PushResult pushResult = null;
        if (StringUtils.isNotBlank(key)) {
            Map<String, String> extraParams = new HashMap<>();
            extraParams.put(key, value);
            if (otherParams != null) {
                extraParams.putAll(otherParams);
            }
            extraParams.put(PushConstants.KEY_MESSAGE_ID, messageId);
            pushResult = jiguangPush.jiguangPush(message.get("push_user_id").toString(),
                    message.get("push_content").toString(), message.get("title").toString(), extraParams);
        } else {
            pushResult = jiguangPush.jiguangPush(message.get("push_user_id").toString(),
                    message.get("push_content").toString());
        }
        // 保存推送消息记录
        this.savePushMessageRecord(message, pushResult);
        return pushResult;
    }

    /**
     * 消息推送 alias
     *
     * @param message
     * @param key
     */
    public PushResult publishMessagePush(Map<String, Object> message, String key, String value) {
        PushResult pushResult = null;
        if (StringUtils.isNotBlank(key)) {
            pushResult = jiguangPush.jiguangPush(message.get("push_user_id").toString(),
                    message.get("push_content").toString(), message.get("title").toString(), key, value);
        } else {
            pushResult = jiguangPush.jiguangPush(message.get("push_user_id").toString(),
                    message.get("push_content").toString());
        }
        // 保存推送消息记录
        this.savePushMessageRecord(message, pushResult);
        return pushResult;
    }

    /**
     * 消息推送 all
     *
     * @param message
     * @param key
     */
    public PushResult publishMessagePushAll(Map<String, Object> message, String key, String value) {
        PushResult pushResult;
        if (StringUtils.isNotBlank(key)) {
            pushResult = jiguangPush.jiguangPushAll(message.get("push_content").toString(), message.get("title").toString(), key, value);
        } else {
            pushResult = jiguangPush.jiguangPushAll(message.get("push_content").toString(), message.get("title").toString());
        }
        // 保存推送消息记录
        this.savePushMessageRecord(message, pushResult);
        return pushResult;
    }

    private void savePushMessageRecord(Map<String, Object> message, PushResult pushResult){
        if (message.get("id") != null) {
            pushMessageRecordService.updatePushStatus(pushResult, message.get("id").toString());
        } else {
            if (pushResult == null || pushResult.error != null) {
                message.put("push_result", "2");
            } else {
                message.put("push_result", "1");
            }
            message.put("push_status", "1");
            message.put("id", UuidUtil.get32UUID());
            pushMessageRecordService.insertMessageRecord(message);
        }
    }
}
